<template>
  <div class="login-bg">
    <div class="login-card">
      <h2 class="login-title">用户登录</h2>
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        label-width="80px"
        class="login-form"
      >
        <!-- 角色选择 -->
        <el-form-item label="角色" prop="role">
          <el-radio-group v-model="loginForm.role">
            <el-radio-button label="BUYER">买家</el-radio-button>
            <el-radio-button label="SELLER">卖家</el-radio-button>
            <el-radio-button label="ADMIN">管理员</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
            clearable
          />
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="loginForm.password"
            :type="passwordVisible ? 'text' : 'password'"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
            clearable
          />
        </el-form-item>
        <!-- 登录按钮 -->
        <el-form-item>
          <el-button
            type="primary"
            class="login-btn"
            @click="handleLogin"
            :loading="isLoggingIn"
            style="width: 100%; background: linear-gradient(90deg, #3b82f6 0%, #6366f1 100%); border: none; color: #fff; font-weight: bold; font-size: 18px;"
          >
            登录
          </el-button>
        </el-form-item>
        <!-- 忘记密码 -->
        <div class="forgot-password">
          <el-link type="primary" @click="showForgotPassword = true">忘记密码?</el-link>
        </div>
      </el-form>
      <div class="register-link">
        还没有账号? <el-link type="primary" @click="goToRegister">立即注册</el-link>
      </div>
    </div>
    <!-- 忘记密码对话框 -->
    <el-dialog
      v-model="showForgotPassword"
      title="重置密码"
      width="500px"
      :close-on-click-modal="false"
    >
      <ForgotPassword @close="showForgotPassword = false" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { View, Hide } from '@element-plus/icons-vue';
import ForgotPassword from '@/components/ForgotPassword.vue';
import { useUserStore } from '@/stores/userStore';
import request from '@/utils/request';

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

const loginForm = reactive({
  role: 'BUYER',
  username: '',
  password: ''
});

const loginFormRef = ref();
const isLoggingIn = ref(false);
const passwordVisible = ref(false);
const showForgotPassword = ref(false);

const loginRules = {
  role: [
    { required: true, message: '请选择登录角色', trigger: 'change' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6位', trigger: 'blur' }
  ]
};

const handleLogin = async () => {
  if (!loginFormRef.value) return;
  for (const key in loginForm) {
    if (typeof loginForm[key] === 'string') {
      loginForm[key] = loginForm[key].trim();
      if (loginForm[key] === '') loginForm[key] = null;
    }
  }
  if (loginForm.role) {
    loginForm.role = loginForm.role.toLowerCase();
  }
  const valid = await loginFormRef.value.validate();
  if (!valid) return;
  isLoggingIn.value = true;
  try {
    const response = await request.post('/api/auth/login', {
      username: loginForm.username,
      password: loginForm.password
    });
    const token = response.token;
    const refreshToken = response.refreshToken;
    const userData = response.user;
    userStore.login(userData, token, refreshToken);
    const roleNames = {
      BUYER: '买家',
      SELLER: '卖家',
      ADMIN: '管理员'
    };
    const roleName = roleNames[userData.role] || '用户';
    ElMessage.success(`登录成功！欢迎${roleName}${userData.username}`);
    const redirectMap = {
      ADMIN: '/admin/dashboard',
      SELLER: '/seller/dashboard',
      BUYER: '/'
    };
    const redirectPath = redirectMap[userData.role] || '/';
    const redirect = route.query.redirect || redirectPath;
    router.push(redirect);
  } catch (error) {
    let errorMsg = '登录失败，请检查用户名和密码';
    if (error.response?.data) {
      if (error.response.data.includes("角色不匹配")) {
        errorMsg = "账户类型与选择角色不匹配";
      } else {
        errorMsg = error.response.data;
      }
    } else if (error.message) {
      errorMsg = error.message;
    }
    ElMessage.error(errorMsg);
  } finally {
    isLoggingIn.value = false;
  }
};
const goToRegister = () => {
  router.push('/register');
};
</script>

<style scoped>
.login-bg {
  min-height: 100vh;
  width: 100vw;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}
.login-card {
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 4px 32px rgba(67,97,238,0.10);
  padding: 48px 48px 32px 48px;
  min-width: 380px;
  max-width: 400px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.login-title {
  font-size: 26px;
  font-weight: bold;
  color: #222;
  margin-bottom: 32px;
  text-align: center;
}
.login-form {
  width: 100%;
}
.login-btn {
  width: 100%;
  height: 44px;
  border-radius: 8px;
  font-size: 18px;
  font-weight: bold;
  background: linear-gradient(90deg, #3b82f6 0%, #6366f1 100%);
  color: #fff;
  border: none;
  box-shadow: 0 2px 8px rgba(67,97,238,0.08);
}
.forgot-password {
  text-align: right;
  margin-top: -10px;
  margin-bottom: 10px;
}
.register-link {
  text-align: center;
  margin-top: 18px;
  color: #888;
  font-size: 15px;
}
</style>